// 文件：server.js
const http = require("http");
const url = require("url");
const querystring = require("querystring");

const server = http.createServer((request, response) => {
    console.log('execute server porcess');
    // 获取 get 请求参数
    let {query} = url.parse(request.url, true);
    // 获取数据类型请求头
    let type = request.headers["content-type"];

    // 接收数据
    let buffers = [];
    request.on("data", data => buffers.push(data));
    request.on("end", () => {
        // 合并数据并设置默认响应头和返回数据
        let data = Buffer.concat(buffers).toString();
        let contentType = "application/json";

        // 判断是否为 get 请求，是则直接返回解析后的数据，不是则判断请求类型
        if (request.method.toLowerCase() === "get") {
            data = JSON.stringify(query);
        } else {
            // 判断请求数据类型并做相应处理
            if (type === "application/x-www-form-urlencoded") {
                console.log(querystring.parse(data))
                data = JSON.stringify(querystring.parse(data));
            } else if (type === "application/json") {
                data = JSON.stringify(JSON.parse(data));
            } else {
                contentType = "text/plain";
            }
        }

        // 设置响应头并返回数据
        response.setHeader("Content-Type", contentType);
        response.end(data);
    });
});

server.listen(3000, () => {
    console.log("server start 3000");
});
